import logging
from logging import handlers


class Logger(object):
    # 日志级别关系映射
    level_relations = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR,
        'crit': logging.CRITICAL
    }

    def __init__(self, filename, level='info', when='midnight', backCount=3,
                 fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger('log')
        self.logger.setLevel(logging.INFO)
        formatter = logging.Formatter('s[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d] - %(message)s',
                                      datefmt='%Y-%m-%d %H:%M:%S')
        # 配置输出日志到终端的 Handler
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(formatter)
        # 配置保存日志到文件的 Handler
        file_handler = logging.FileHandler(filename, encoding='utf-8')
        file_handler.setFormatter(formatter)
        # 添加 Handler
        self.logger.addHandler(stream_handler)
        self.logger.addHandler(file_handler)


if __name__ == '__main__':
    log = Logger('dialogue.log', level='debug')
    log.logger.debug('debug')
    log.logger.info('info')
    log.logger.warning('警告')
    log.logger.error('报错')
    log.logger.critical('严重')
    Logger('error.log', level='error').logger.error('error')
